<?php

class CustomerController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
	
	public $defaultAction='admin';
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // only allow authenticated user to get access to the system.
				'actions'=>array('view','create','update','admin','quickSearch','delete','deleteAddressLog', 'ajaxAddressSearch'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{	
		//check if current user has right to view this customer's info.
		if(!Yii::app()->user->checkAccess('customerInfoAccess',array('customerId'=>$id)))
			throw new CHttpException(403,'You do not have permission to view this customer.');
		
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	public function actionDeleteAddressLog($addressLogId){
		$addressLog=CustomerAddressLog::model()->findByPk($addressLogId);
		$customerId=$addressLog->customer->id;
		if(!Yii::app()->user->checkAccess('customerInfoAccess',array('customerId'=>$customerId)))
			throw new CHttpException(403,'You do not have permission to update this customer.');
		$addressLog->delete();
		$this->redirect(array('view','id'=>$customerId));
	}
	
	public function actionQuickSearch($term) {
		$criteria=new CDbCriteria();
		if(is_numeric($term)){
			$criteria->compare('id', $term);
		}else{
			$termPieces=explode(' ', $term,2);
			if(count($termPieces)>1){
				$firstName=$termPieces[0];
				$lastName=$termPieces[1];
				$criteria->compare('firstName', $firstName,true);
				$criteria->compare('lastName', $lastName,true);
			}else{
				$firstName=$lastName=$term;				
				$criteria->compare('firstName', $firstName,true,'OR');
				$criteria->compare('lastName', $lastName,true,'OR');		
			}			
		}
		
		// Limit result based on the role.
		if(!Yii::app()->user->checkAccess('manager'))
		{
			//if not manager, limit should apply.
			
			if(User::getCurrentUser()->teamLeader)
				$criteria->compare('teamId', User::getCurrentUser()->teamId);
			else
				$criteria->compare('createUserId', User::getCurrentUser()->id);
		}
		
		$customers=Customer::model()->findAll($criteria);
		$returnVal = array();
		foreach($customers as $customer)
		{
			$birth = empty($customer->dateOfBirth) ? 'Not Set' : $customer->dateOfBirth;
			$returnVal[] = array('label'=> $customer->getFullName().
					' ('.$birth.')',
					'id'=>$customer->getAttribute('id'),
			);
		}
		header("Cache-Control: no-cache, must-revalidate");
		header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
		echo CJSON::encode($returnVal);
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($copyFrom=NULL)
	{
		$model=new Customer;
		$model->valueStar=3;

		// Uncomment the following line if AJAX validation is needed
 		$this->performAjaxValidation($model);
 		$copyFromCustomer=null;
 		if($copyFrom){
 			if($copyFromCustomer=Customer::model()->findByPk($copyFrom)){
	 			$copyFields=array(
		 			'contactPhone',
					'contactMobile',
					'contactFax',
					'email',
					'postalAddress',
					'postalSuburb',
					'postalPostcode',
					'postalState',
					'postalCountry',
					'physicalAddress',
					'physicalSuburb',
					'physicalPostcode',
					'physicalState',
					'physicalCountry',
					'BankName',
					'BankAccountNumber',
	 			);
	 			foreach ($copyFields as $field) {
	 				$model->$field=$copyFromCustomer->$field;
	 			}
 			}
 		}

		if(isset($_POST['Customer']))
		{
			$model->attributes=$_POST['Customer'];
			$model->teamId=User::getCurrentUser()->teamId;
			if($model->save()){
				//@mkdir(Yii::app()->params['attachmentFileLocation'].DIRECTORY_SEPARATOR.$model->id);
				if($copyFrom&&!empty($_POST['createRelation'])){
					$relation=new CustomerRelation();
					$relation->fromCustomer=$model->id;
					$relation->toCustomer=$copyFrom;
					$relation->relationText=$_POST['createRelation'];
					$relation->save();
				}
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('create',array(
			'model'=>$model,
			'copyFromCustomer'=>$copyFromCustomer
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		if(!Yii::app()->user->checkAccess('customerInfoAccess',array('customerId'=>$id)))
			throw new CHttpException(403,'You do not have permission to update this customer.');

		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Customer']))
		{
			$this->processAddressChange($model,$_POST['Customer']);
			$model->attributes=$_POST['Customer'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	private function processAddressChange($customer,$attributes) {
		$addressAttributes=array('postalAddress','postalSuburb','postalPostcode','postalState','postalCountry');
		$changed=false;
		foreach ($addressAttributes as $addressAttribute) {
			if($customer->$addressAttribute!=$attributes[$addressAttribute]){
				$changed=true;
			}
		}
		if($changed){
			$addressLog=new CustomerAddressLog();
			$addressLog->customerId=$customer->id;
			foreach ($addressAttributes as $addressAttribute) {
				$addressLog->$addressAttribute=$customer->$addressAttribute;
			}
			$addressLog->save();
		}
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(!Yii::app()->user->checkAccess('customerInfoAccess',array('customerId'=>$id)))
			throw new CHttpException(403,'You do not have permission to update this customer.');
		
		
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
/*	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Customer');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}*/

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Customer('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Customer']))
			$model->attributes=$_GET['Customer'];
		
		// if current user is not manager and reception, he is not able to browse all customer record.
		if(!Yii::app()->user->checkAccess('manager') && !User::getCurrentUser()->isReception()){
			if(!User::getCurrentUser()->teamLeader){
				$model->createUserId=User::getCurrentUser()->id;
			}else{
				$model->teamId=User::getCurrentUser()->teamId;
			}
		}

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 * @return Customer
	 */
	public function loadModel($id)
	{
		$model=Customer::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='customer-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	
	public function actionAjaxAddressSearch($term) {
		if(Yii::app()->request->isAjaxRequest && isset($term) && !empty($term)){	
			$sql = sprintf('SELECT postalAddress AS address, postalSuburb AS suburb, postalState AS state, 
				 			postalCountry AS country, postalPostcode AS postcode FROM dycrm_customer
							WHERE postalAddress LIKE "%s" AND createUserId = %d
							UNION
							(
							SELECT physicalAddress AS address, physicalSuburb AS suburb, physicalState AS state, 
							physicalCountry AS country, physicalPostcode AS postcode FROM dycrm_customer
							WHERE physicalAddress LIKE "%s" AND createUserId = %d);', 
							"%".trim($term)."%", Yii::app()->user->id, "%".trim($term)."%", Yii::app()->user->id);
			$addresses = Yii::app()->db->createCommand($sql)->queryAll();
			$returnVal = array();
			foreach ($addresses as $address){
				$returnVal[] = array(
						'label'=>$address['address'].", ".$address["suburb"]." ".$address["state"]." ".$address["country"]." ".$address["postcode"],
						'address'=> $address['address'],
						'suburb'=> $address["suburb"],
						'state'=> $address["state"],
						'country'=> $address["country"],
						'postcode'=> $address["postcode"]
				);
			}
			
			header("Cache-Control: no-cache, must-revalidate");
			header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
			echo CJSON::encode($returnVal);
		}
	}
}
